package net.libra.animatedBitmap
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	
	/**
	 * 位图动画基类
	 * @author elvisjiang
	 */ 
	public class BaseAnimateObject extends Sprite implements IJTickable
	{
		
		private var bitmap:Bitmap;
		
		private var bmdList:Vector.<BitmapData>;
		
		/**
		 * 帧率
		 */
		protected var frameRate:int;
		
		/**
		 * 每帧需要的毫秒数
		 */
		protected var rateTimer:int;
		protected var curFrame:int;
		private var totalFrame:int;
		protected var frameTimer:int;
		private var playing:Boolean;
		
		public function BaseAnimateObject(name:String = "",frameRate:int = 0)
		{
			super();
			this.name = name;
			bitmap = new Bitmap();
			this.addChild(bitmap);
			
			frameTimer = 0;
			if(frameRate == 0){
				this.addEventListener(Event.ADDED_TO_STAGE,add_stage);
			}else{
				this.setFrameRate(frameRate);
			}
		}

		public function get _name():String
		{
			return this.name;
		}

		protected function add_stage(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE,add_stage);
			this.setFrameRate(stage.frameRate);
		}
		
		protected function setFrameRate(frameRate:int):void {
			this.frameRate = frameRate;
			this.rateTimer = 1000 / frameRate;
		}
		
		public function play():void{
			this.playing = true;
		}
		
		public function stop():void{
			this.playing = false;
		}
		/**
		 * 具体动画覆盖方法
		 */ 
		public function setBmdList(bmd:Vector.<BitmapData>):void{
			this.bmdList = bmd;
			this.totalFrame = bmd.length;
			this.curFrame = 0;
			this.stop();
		}
		
		public function tick(interval:Number):void{
			if (!this.bmdList) return;
			frameTimer -= interval;
			while (frameTimer < 0) {
				if (this.curFrame >= totalFrame) {
					this.curFrame = 0;
				}
				if(this.playing)
					this.bitmap.bitmapData = this.bmdList[curFrame++];
				frameTimer += rateTimer;
			}
		}
		
		public function getWidth():int{
			return this.bitmap.bitmapData ? this.bitmap.bitmapData.width : -1;
		}
		
		public function getHeight():int{
			return this.bitmap.bitmapData ? this.bitmap.bitmapData.height : -1;
		}
		public function destory():void
		{
			this.bitmap = null;
			for each(var bitmapdata:BitmapData in this.bmdList)
			{
				bitmapdata.dispose();
				bitmapdata = null;
			}
			this.bmdList = null;
		}
	}
}